<template>
  <div id="horse"
  v-loading="loadingBuy">
    <el-scrollbar class="scroll-view">
      <div class="scroll-content">
        <div class="head-section h-left">
          <div style="margin-left: 10px;margin-right:10px;">{{horseDetail.name}}</div>
          <div v-if="isSale">For sale = {{ buyPrice }} ETH</div>
          <el-rate
              v-model="horseDetail.rateValue"
              disabled
              class="rate-cell" style="margin-left:20px;">
          </el-rate>
        </div>

        <div class="body-section">
        <el-row>
            <el-col class="detail-card-col">
              <img :src="horseDetail.imgUrl" width="200px" height="200px"/>
            </el-col>

            <el-col class="detail-card-col" style="margin-left: -50px;">
            <ve-radar
                width="300px"
                height="220px"
                :data="horseDetail.chartData"
                :settings="chartSettings"
                :tooltip-visible="false"
                :legend-visible="true"
                :colors="colors"
                :extend="extend"
                class="detail-skill-charts">
                </ve-radar>
            </el-col>

            <el-col class="detail-card-col" style="margin-left: 20px;">
            <div class="horse-info font-m">
                Other Attributes:
                <!-- <div>height: 180cm</div>
                <div>weight: 450KG</div>
                <div>Coat Color: Bay</div>
                <div>Sex: Stallion</div> -->
                <div class="top-20"></div>
                <div class="font-s" style="color: gray;">Stability: {{horseDetail.stabilityValue}}</div>
                <div class="font-s" style="color: gray;">Robustness: {{horseDetail.robustnessValue}}</div>
                <!-- <div class="top-20"></div>
                <div>Brief: ???</div>
                <div class="top-20"></div>
                <div>Sire: ???</div>
                <div>Dam: ???</div>
                <div>Foals: ???</div> -->
            </div>
            </el-col>
        </el-row>
        </div>

        <div class="foot-section">
            <el-card v-if="isSaleNotMe" class="opt-card-cell">
                <div>Buy now Price</div>
                <div>{{ buyPrice }} ETH</div>
                <el-button style="float: right;margin-top:0px;" type="primary" @click="onBuy">Buy Now</el-button>
            </el-card>
            <el-card v-if="isMineNotSale" class="opt-card-cell">
                <el-button style="float: right;margin-top:40px;" type="warning" @click="onSell">Sell</el-button>
            </el-card>
            <el-card v-if="isMineOnSale" class="opt-card-cell">
                <div class="h-left">
                    <span>
                        <div>Buy now price</div>
                        <div>{{ cancelSalePrice }} ETH</div>
                    </span>
                    <span style="margin-left: 20px;">
                        <div>Time left</div>
                        <div>{{ cancelSaleTimeLeft }} Days</div>
                    </span>
                </div>

                <el-button style="float: right;margin-top:0px;" type="info" @click="onCancelSale">Cancel sale</el-button>
            </el-card>
            <el-card v-if="isNotMine" class="opt-card-cell">
                <div>Owner online!</div>
                <el-button style="float: right;margin-top:0px;" type="success" @click="onChallenge">Challenge</el-button>
            </el-card>
        </div>
      </div>
    </el-scrollbar>

    <!-- 购买 对话框 -->
    <el-dialog
    title="You're about to buy"
    :visible.sync="buyDialogVisible"
    width="30%"
    :before-close="handleDialogClose">
    <span>By clicking the button below, you will receive the Horse {{ buyHorseCode }} and spend {{ buyPrice }} ETH.</span>
    <span slot="footer" class="dialog-footer">
        <el-button @click="buyDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="onBuyConfirmed">Buy the horse</el-button>
    </span>
    </el-dialog>

    <!-- 卖出 对话框 -->
    <el-dialog
    title=""
    :visible.sync="sellDialogVisible"
    width="40%"
    :before-close="handleDialogClose">
    <span class="h-justify" style="width: 100%;">
        <span> You're about to sell {{ sellHorseName }} </span>
        <span>
            <div class="h-row-right">
                <span>Price: </span>
                <span><el-input-number v-model="sellPrice" controls-position="right" :precision="4" :step="0.0001" :min="0.0001" label="Price"></el-input-number></span>
                <span>ETH</span>
            </div>
            <div class="h-row-right" style="margin-top: 8px;">
                <span>Shelf duration: </span>
                <span><el-input-number v-model="sellDays" controls-position="right" :min="1" :max="100" label="Shelf duration"></el-input-number></span>
                <span>Days</span>
            </div>

        </span>
    </span>

    <span slot="footer" class="dialog-footer">
        <el-button @click="sellDialogVisible = false">Cancel</el-button>
        <el-button type="warning" @click="onSellHorse">OK, Sell this horse</el-button>
    </span>
    </el-dialog>

    <!-- 取消卖出 对话框 -->
    <el-dialog
    title="You're about to cancel this sale"
    :visible.sync="cancelSaleDialogVisible"
    width="30%"
    :before-close="handleDialogClose">
    <span></span>
    <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSaleDialogVisible = false">Let me think</el-button>
        <el-button type="info" @click="onCancelConfirmed">OK, Cancel this sale</el-button>
    </span>
    </el-dialog>

    <!-- 发起挑战 对话框 -->
    <el-dialog
    title=""
    :visible.sync="startChallengeDialogVisible"
    width="60%"
    :before-close="handleDialogClose">
    <span
      v-loading="challengeLoading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      class="h-justify v-center">
      <span>
        <div>Select your Horse</div>
        <el-card :body-style="{ padding: '0px' }" class="card-cell h-center" @click.native="onHorseClicked(selectedHorse.id)">
          <ve-radar
            width="280px"
            height="220px"
            :data="selectedHorse.chartData"
            :settings="chartSettings"
            :tooltip-visible="false"
            :legend-visible="true"
            :colors="colors"
            :extend="extend"
            class="skill-charts"></ve-radar>

          <el-rate
            v-model="selectedHorse.rateValue"
            disabled
            class="rate">
          </el-rate>

          <div class="card-bottom h-justify">
            <img class="circle" :src="selectedHorse.imgUrl" width="100px" height="100px">
            <span class="v-bottom" style="color: #00ff00;">
              <div>{{ selectedHorse.name }}</div>
            </span>
            <span class="trailing-4 v-bottom">
              <div >Gen{{selectedHorse.generationNum}}</div>
            </span>
          </div>
        </el-card>
      </span>

      <span>
        VS
        <div>
          Bets: 10 HSD
        </div>
      </span>

      <span>
        <div>Opponent</div>
        <el-card :body-style="{ padding: '0px' }" class="card-cell h-center" @click.native="onHorseClicked(horseDetail.id)">
          <ve-radar
            width="280px"
            height="220px"
            :data="horseDetail.chartData"
            :settings="chartSettings"
            :tooltip-visible="false"
            :legend-visible="true"
            :colors="colors"
            :extend="extend"
            class="skill-charts"></ve-radar>

          <el-rate
            v-model="horseDetail.rateValue"
            disabled
            class="rate">
          </el-rate>

          <div class="card-bottom h-justify">
            <img class="circle" :src="horseDetail.imgUrl" width="100px" height="100px">
            <span class="v-bottom" style="color: #00ff00;">
              <div>{{ horseDetail.name }}</div>
            </span>
            <span class="trailing-4 v-bottom">
              <div >Gen{{horseDetail.generationNum}}</div>
            </span>
          </div>
        </el-card>
      </span>
    </span>
    <span slot="footer" class="dialog-footer">
      <el-button type="success" @click="onChallengeConfirmed">Challenge</el-button>
    </span>
    </el-dialog>

    <!-- 用户当前没有马 -->
    <el-dialog
    title=""
    :visible.sync="challengeNoHorseDialogVisible"
    width="30%"
    :before-close="handleDialogClose">
    <span></span>
    <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="challengeNoHorseDialogVisible = false">OK</el-button>
    </span>
    </el-dialog>

    <!-- 接受挑战 对话框 -->

  </div>
</template>

<script>
  export default {
    name: 'horse',
    data: function () {
      this.extend = {
        series: {
          label: {
            normal: {
              show: true
            }
          }
        }
      }

      this.chartSettings = {
        dimension: [],
        metrics: ['Speed', 'Acceleration', 'Strength', 'Endurance', 'Agile', 'Balancing', 'Bouncing'],
        dataType: 'normal'
      }

      this.colors = [
        '#00000000',
        '#2f4554'
      ]

      return {
        horseId: 0,

        loadingBuy: false,

        challengeLoading: false,
        currentWalletAddress: '',
        horseWalletAddress: '',
        horseDetail: {},
        isSale: true,

        isSaleNotMe: false,
        isMineNotSale: false,
        isMineOnSale: false,
        isNotMine: false,

        validHorses: [],

        value5: 2,
        chartData: {
          rows: []
        },
        buyDialogTitle: '',
        buyDialogVisible: false,
        buyPrice: 1.009,
        buyeeName: 'PANES',
        buyHorseCode: '#32323232',
        buyHorseName: 'KITTY',

        sellPrice: 0.0001,
        sellDays: 1,
        sellHorseName: '',
        sellDialogVisible: false,

        cancelSalePrice: 1.99,
        cancelSaleTimeLeft: 1,
        cancelSaleDialogVisible: false,

        startChallengeDialogVisible: false,
        matchId: 0,
        selectedHorseId: 0,
        selectedHorse: {},

        acceptChallengeDialogVisible: false,

        rejectChallengeDialogVisible: false,

        challengeNoHorseDialogVisible: false,

        auctionDetail: {}
      }
    },
    mounted () {
      var horseId = this.$route.query.id

      this.buyHorseCode = '#' + horseId

      // 获取马详情
      this.getHorseDetail(horseId)

      this.horseId = horseId

      // 查询用户信息
      this.$root.callMatch({
        params: null,
        methodName: API.GET_ACCOUNTS,
        methodType: 'GET',
        success: (data) => {
          console.log('currentWalletAddress = ' + data)
          this.currentWalletAddress = data
        },
        failure: null
      })
    },
    methods: {
      handleTabClick () {
        return true
      },
      // 购买
      onBuy () {
        // this.buyDialogTitle = "You're about to buy " + this.buyHorseName + ' ' + this.buyHorseCode
        this.buyDialogVisible = true
      },
      onBuyConfirmed () {
        this.buyDialogVisible = false
        this.loadingBuy = true

        this.$root.callMatch({
          isProtected: false,
          // 10000000000000000 = 0.01 eth
          // tokenId
          params: parseInt(this.horseDetail.id),
          methodName: API.BID,
          methodType: 'POST',
          amount: 90000000000000000,
          event: 'Transfer',
          success: data => {
            this.loadingBuy = false

            console.log('buy = ' + JSON.stringify(data))

            this.postBid = data

            this.getHorseDetail(this.horseId)
          },
          failure: null
        })
      },
      // 通用关闭
      handleDialogClose (done) {
        done()
      },
      // 卖出
      onSell () {
        this.sellHorseName = this.buyHorseCode

        this.sellDialogVisible = true
      },
      onCancelSale () {
        this.cancelSaleDialogVisible = true
      },
      onCancelConfirmed () {
        this.cancelSaleDialogVisible = false
        this.loadingBuy = true

        this.$root.callMatch({
          isProtected: false,
          // token_id
          params: parseInt(this.horseDetail.id),
          methodName: API.CANCEL_AUCTION,
          methodType: 'POST',
          event: 'cancelSell',
          success: data => {
            console.log('cancel = ' + JSON.stringify(data))

            this.cancelEvent = data

            this.loadingBuy = false

            this.getHorseDetail(this.horseId)
          },
          failure: null
        })
      },
      // 挑战
      onChallenge () {
        // 用户当前是否有马
        this.$root.callMatch({
          isProtected: true,
          methodName: API.TOKENS_OF_OWNER,
          methodType: 'GET',
          success: data => {
            console.log('getHorses = ' + JSON.stringify(data))

            if (data.length > 0) {
              // 获取一匹马
              this.selectedHorseId = data[0]

              this.$root.callMatch({
                isProtected: false,
                params: parseInt(this.selectedHorseId),
                methodName: API.GET_HORSE,
                methodType: 'GET',
                success: data => {
                  console.log(JSON.stringify(data))
                  var gen = data[0] // 基因
                  var speedValue = parseInt(gen.slice(0, 2))
                  var accelerationValue = parseInt(gen.slice(2, 4))
                  var strengthValue = parseInt(gen.slice(4, 6))
                  var enduranceValue = parseInt(gen.slice(6, 8))
                  var agileValue = parseInt(gen.slice(8, 10))
                  var balancingValue = parseInt(gen.slice(10, 12))
                  var bouncingValue = parseInt(gen.slice(12, 14))
                  var reactionValue = parseInt(gen.slice(14, 16))

                  var generationNum = data[7]

                  var horse = {}

                  horse.id = this.selectedHorseId
                  horse.name = HORSE_NAMES[horse.id]
                  horse.imgUrl = require(`../../assets/img/horses/${this.selectedHorseId}.jpg`)
                  horse.chartData = {
                    rows: [
                      { 'Speed': 100,
                        'Acceleration': 100,
                        'Strength': 100,
                        'Endurance': 100,
                        'Agile': 100,
                        'Balancing': 100,
                        'Bouncing': 100,
                        'Reaction': 100
                      },
                      {
                        'Speed': speedValue,
                        'Acceleration': accelerationValue,
                        'Strength': strengthValue,
                        'Endurance': enduranceValue,
                        'Agile': agileValue,
                        'Balancing': balancingValue,
                        'Bouncing': bouncingValue,
                        'Reaction': reactionValue
                      }
                    ]
                  }

                  var rateValue = (speedValue + accelerationValue + strengthValue + enduranceValue + agileValue + balancingValue + bouncingValue + reactionValue) / 160
                  horse.rateValue = Math.ceil(rateValue)

                  horse.generationNum = parseInt(generationNum)

                  this.selectedHorse = horse

                  this.validHorses = []

                  this.validHorses.push(horse)
                  this.validHorses.push(this.horseDetail)

                  // 显示挑战框
                  this.startChallengeDialogVisible = true
                },
                failure: null
              })
            } else {
              this.challengeNoHorseDialogVisible = true
            }
          },
          failure: null
        })
      },
      onChallengeConfirmed () {
        this.challengeLoading = true

        this.$root.callMatch({
          isProtected: false,
          params: [parseInt(this.selectedHorseId), parseInt(this.horseDetail.id), this.horseWalletAddress],
          methodName: API.CHALLENGE,
          methodType: 'POST',
          event: 'Challenge',
          success: data => {
            console.log('CHALLENGE = ' + JSON.stringify(data))

            this.challengeLoading = false
            this.startChallengeDialogVisible = false

            // address 发起人 address 欲挑战的玩家 int 发起的马 int 欲挑战的马 int 赌注 int 阶段 总是1(发起挑战中) int 比赛id
            this.matchId = data[0].chllengeId

            this.$router.push({
              path: '/match',
              query: {
                id: this.matchId,
                isChallenger: 1
              }
            })
          },
          failure: null
        })
      },
      // 接受挑战
      onAcceptChalenge () {
        this.acceptChallengeDialogVisible = true
      },
      onSellHorse () {
        this.sellDialogVisible = false
        this.loadingBuy = true

        this.$root.callMatch({
          // isProtected: false,
          params: [parseInt(this.horseDetail.id), 10000000000000000, 1000000000000000000, 36000],
          methodName: API.SELL_HORSE,
          methodType: 'POST',
          event: 'Sell',
          success: data => {
            console.log('horse sell = ' + JSON.stringify(data))

            this.loadingBuy = false

            this.getHorseDetail(this.horseId)
          },
          failure: null
        })
      },
      // 接口
      getHorseDetail (horseId) {
        console.log('getHorseDetail = ' + horseId)

        this.$root.callMatch({
          isProtected: false,
          params: parseInt(horseId),
          methodName: API.GET_HORSE_WITH_AUCTION,
          methodType: 'GET',
          success: data => {
            console.log(JSON.stringify(data))

// ["01235601564089748905641560484890","1530164343","0","0","0","0","10","0",true,false]
            this.isSale = data[9]

            var gen = data[0] // 基因
            var speedValue = parseInt(gen.slice(0, 2))
            var accelerationValue = parseInt(gen.slice(2, 4))
            var strengthValue = parseInt(gen.slice(4, 6))
            var enduranceValue = parseInt(gen.slice(6, 8))
            var agileValue = parseInt(gen.slice(8, 10))
            var balancingValue = parseInt(gen.slice(10, 12))
            var bouncingValue = parseInt(gen.slice(12, 14))
            var reactionValue = parseInt(gen.slice(14, 16))

            var robustnessValue = parseInt(gen.slice(16, 18))
            var stabilityValue = parseInt(gen.slice(18, 20))

            this.horseDetail.robustnessValue = robustnessValue
            this.horseDetail.stabilityValue = stabilityValue
            this.horseDetail.id = horseId
            this.horseDetail.name = HORSE_NAMES[horseId]
            this.horseDetail.imgUrl = require(`../../assets/img/horses/${horseId}.jpg`)
            this.horseDetail.chartData = {
              rows: [
                { 'Speed': 100,
                  'Acceleration': 100,
                  'Strength': 100,
                  'Endurance': 100,
                  'Agile': 100,
                  'Balancing': 100,
                  'Bouncing': 100,
                  'Reaction': 100
                },
                {
                  'Speed': speedValue,
                  'Acceleration': accelerationValue,
                  'Strength': strengthValue,
                  'Endurance': enduranceValue,
                  'Agile': agileValue,
                  'Balancing': balancingValue,
                  'Bouncing': bouncingValue,
                  'Reaction': reactionValue
                }
              ]
            }

            var rateValue = (speedValue + accelerationValue + strengthValue + enduranceValue + agileValue + balancingValue + bouncingValue + reactionValue) / 160
            this.horseDetail.rateValue = Math.ceil(rateValue)

            // 获取挂牌
            // this.getIsHorseAuction(parseInt(horseId))

            // 获取马主人
            this.$root.callMatch({
              isProtected: false,
              params: parseInt(this.horseDetail.id),
              methodName: API.OWNER_OF,
              methodType: 'GET',
              success: data => {
                console.log('OWNER_OF = ' + JSON.stringify(data))
                this.horseWalletAddress = data

                if (this.horseWalletAddress !== this.currentWalletAddress) {
                  if (this.isSale) {
                    this.isSaleNotMe = true
                  }

                  this.isNotMine = true

                  this.isMineOnSale = false
                  this.isMineNotSale = false
                }

                if (this.horseWalletAddress === this.currentWalletAddress) {
                  this.isNotMine = false
                  this.isSaleNotMe = false

                  if (!this.isSale) {
                    this.isMineNotSale = true
                    this.isMineOnSale = false
                  } else {
                    this.isMineOnSale = true
                    this.isMineNotSale = false
                  }
                } else {
                  this.isMineNotSale = false
                  this.isMineOnSale = false
                }
              },
              failure: null
            })

            // 获取价格
            this.$root.callMatch({
              isProtected: false,
              params: parseInt(horseId),
              methodName: API.GET_CURRENT_PRICE,
              methodType: 'GET',
              success: data => {
                console.log('get current price = ' + JSON.stringify(data))

                this.buyPrice = parseInt(data) / 1000000000000000000

                this.cancelSalePrice = this.buyPrice
              },
              failure: null
            })
          },
          failure: null
        })
      },
      getHorseAuction (horseId) {
        this.$root.callMatch({
          isProtected: false,
          params: horseId,
          methodName: API.GET_AUCTION,
          methodType: 'GET',
          success: data => {
            console.log('selling = ' + JSON.stringify(data))

            // address 挂牌人address, int 起始价格, int 结束价格, int 挂牌时间秒, int 生效时间
            this.auctionDetail = {
              startTime: data[4]
            }

            this.cancelSaleTimeLeft = this.auctionDetail.startTime || '未指定'
          },
          failure: null
        })
      },
      getIsHorseAuction (horseId) {
        this.$root.callMatch({
          isProtected: false,
          params: horseId,
          methodName: API.IS_ON_AUCTION,
          methodType: 'GET',
          success: data => {
            console.log('selling = ' + JSON.stringify(data))

            if (data > 0) {
              this.sellDialogVisible = true

              this.getHorseAuction(horseId)
            } else {
              this.sellDialogVisible = false
            }
          },
          failure: null
        })
      }
    }
  }

  import { API, HORSE_NAMES } from '../../util/constants'
</script>

<style scoped>
#horse {
  width: 100%;
  height: 100%;
  margin-top: 78px;
  margin-left: 12px;
}

.scroll-view {
  height: 100%;
}

.scroll-content {
  margin-top: 10px;
  margin-bottom: 10px;
}

.head-section {
  height: auto;
}

.body-section {
  margin-top: 20px;
}

.foot-section {
    margin-top: 60px;
    width: 100%;
}

.detail-card-col {
  width: 20%;
}

.horse-info {
  background-color: rgba(0, 0, 0, 0);
  width: 100%;
  height: 100%;
}

.opt-card-cell {
    margin-top: 20px;
    width: 65%;
    height: 120px;
}

.opt-card-cell-mul {
    margin-top: 20px;
    width: 65%;
    height: 120px;
    display: flex;
    flex-direction: row;
}

/* 马区域的css */

.card-cell {
  padding: 10px;
  height: 380px;
  max-width: 360px;
}

.card-col {
  width: 300px;
  margin: 4px;
}

.card-bottom {
  margin-top: 8px;
}

.detail-skill-charts {
  max-height: 290px;
  max-width: 400px;
}

.skill-charts {
  max-height: 290px;
  max-width: 400px;
}

.card-down {
  bottom: 0px;
}

.rate {
  margin-top: 10px;
}
</style>
